package com.appspot.didit.client.workitem;

import java.util.Date;

import com.appspot.didit.client.BaseView;
import com.appspot.didit.client.tag.TagManager;
import com.appspot.didit.client.user.UserManager;
import com.appspot.didit.client.util.Util;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;

public class CreateWorkitemPresenterImpl implements CreateWorkitemPresenter {
	private final WorkitemServiceAsync workitemService = GWT.create(WorkitemService.class);
	private final View view;
	/*
	 * 0 - available
	 * 1 - busy
	 */
	private int status = 0;
	
	@Inject
    public CreateWorkitemPresenterImpl(final HandlerManager eventBus, final View view) {

            this.view = view;
            view.getSaveButtonClickHandlers().addClickHandler(new ClickHandler() {
				public void onClick(ClickEvent event) {
					if(status == 0) {
						createWorkitem(eventBus);
					}
				}
            });
            
            view.getKeyPressHandler().addKeyPressHandler(new KeyPressHandler() {
				@Override
				public void onKeyPress(KeyPressEvent event) {
					if(status == 0) {
						if (event.getCharCode() == KeyCodes.KEY_ENTER) {
							 createWorkitem(eventBus);
						 }
					}
				}
            });

    }
	
	@SuppressWarnings("unchecked")
	private void createWorkitem(final HandlerManager eventBus) {
		String description = view.getDescription().getValue().toString();
		String hour = view.getHour().getValue().toString();
		String minute = view.getMinute().getValue().toString();
		final String tag = view.getTag().getValue().toString();
		Date date = view.getDate().getValue();
		if(validate(hour+minute, tag, date)) {
			if (description == null || description.equals("")) {
				description = tag;
			}
			double hours = Util.getHoursFromIntegers(Integer.parseInt(hour), Integer.parseInt(minute));
			Workitem wi = new Workitem(description, hours, tag, date, UserManager.getInstance().getUserId());
			view.getWidget().setStyleName("waiting-blocker");
			status = 1;
			workitemService.save(wi, new AsyncCallback() {
                public void onFailure(Throwable caught) {
                	status = 0;
                	view.getWidget().removeStyleName("waiting-blocker");
                    GWT.log("Failed to create a new Workitem", caught);
                }
                public void onSuccess(Object result) {
                	status = 0;
                	view.getWidget().removeStyleName("waiting-blocker");
                	GWT.log("successfully created a new Workitem", null);
                	Workitem wi = (Workitem)result;
                	WorkitemManager.getInstance().addWorkitem(wi);
                	TagManager.getInstance().saveTags(tag, wi);
                	eventBus.fireEvent(new WorkitemCreatedEvent());
                    view.reset();
                }		
            });
		}
	}
    
    @SuppressWarnings("deprecation")
	private boolean validate(String duration, String tag, Date date) {
    	String hint = "";
    	boolean valid = true;
    	
    	if(duration == null || duration.trim().equals("")) {
    		hint = hint + "Dauer darf nicht leer sein! ";
    		valid = false;
		} else {
			if(!duration.matches("[0-9]*\\.?[0-9]*")) {
				hint = hint + "Dauer darf nur aus Ziffer bestehen! ";
				valid = false;
			}
			if(duration.matches("[0]*")) {
				hint = hint + "Dauer darf nicht 0 sein! "; 
				valid = false;
			}	
		}
		if(tag.trim().equals("") || tag == null) {
			hint = hint + "Projekte d\u00fcrfen nicht leer sein! ";
			valid = false;
		}
		if(date != null) {
			Date today = new Date();
			today.setHours(23);
			today.setMinutes(59);
			today.setSeconds(59);
			
			if(date.after(today)) {
				hint = hint + "Datum darf nicht in der Zukunft sein! ";
				valid = false;
			}
			
			//Input is valid only when it was less than 5 days before
			today.setHours(0);
			today.setMinutes(0);
			today.setSeconds(0);
			today.setTime(today.getTime() - 5*24*60*60*1000);
			if(date.before(today)) {
				hint = hint + "Datum ist ung\u00fcnltig! ";
				valid = false;
			}
		} else {
			hint = hint + "Datum ist ung\u00fcnltig! ";
			valid = false;
		}
		if(!valid) {
			view.getHint().setText(hint);
		}
		return valid;
    }

    	
    public View showCreateWorkitem() {
            return view;
    }

    public BaseView getView() {
            return view;
    }
}
